package com.boe.server.register.service.impl;

import com.boe.server.register.mapper.SysUserMapper;
import com.boe.server.register.pojo.dto.SysUserDetail;
import com.boe.server.register.pojo.po.SysRole;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserMapper sysUserMapper;

    public UserDetailsServiceImpl(SysUserMapper sysUserMapper) {

        this.sysUserMapper = sysUserMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<SysUserDetail> userDetail = sysUserMapper.selectUserDetails(username);
        if (userDetail.isEmpty()) throw new UsernameNotFoundException(username);
        String[] roles = userDetail.get(0).getRoles().stream().map(SysRole::getRoleKey).toArray(String[]::new);
        return User
                .withUsername(username)
                .password(userDetail.get(0).getPassword())
                .disabled(userDetail.get(0).getStatus() == 1)
                .roles(roles)
                .build();
    }
}
